//
//  UploadPicVC.m
//  KuWoCan
//
//  Created by hwd on 17/3/17.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "UploadPicVC.h"
#import "NWPicManageRequest.h"
#import "PicListModel.h"
#import "PicPageListModel.h"

static NSString *const TextViewDefaultString = @"照片描述";

@interface UploadPicVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextViewDelegate>

//@property (nonatomic,strong) NSMutableArray *picMutableArr;

@property (nonatomic,strong) UICollectionView *collectView;

//@property (nonatomic,strong) UIButton *confirmBtn;

@property (nonatomic,strong) UITextView *txtView;

@end

@implementation UploadPicVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //数据源
    
    if (_picMutableArr.count<=0) {
        _picMutableArr = [NSMutableArray array];
//        _picParaArr = [NSMutableArray array];
    }else
    {
        PicListModel *model = self.picMutableArr[0];
        _describStr = model.title;
    }
    //添加图片页面,pop出来后,必须请求数据
    if (_isChange) {
        [self getDataWithPage:@"1" pageSize:@"50"];
    }
    [self configUI];
}

#pragma mark - Data request
- (void)getDataWithPage:(NSString *)page pageSize:(NSString *)pageSize
{
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestQueryPicWithProcessId:_orderId pageNo:page pageSize:pageSize type:[NSString stringWithFormat:@"%zd", _picType]];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            //当前显示的数据
            if(!self.picMutableArr)
            {
                self.picMutableArr = [NSMutableArray array];
            }
            PicPageListModel *pageModel = [[PicPageListModel alloc] initWithDictionary:result[@"pageList"] error:nil];
            if ([pageModel.count integerValue] > 0)
            {
                self.picMutableArr = pageModel.list.mutableCopy;
            }
            if (_collectView)
            {
                [_collectView reloadData];
            }
            
        }
    }];
}


#pragma mark - Config UI
- (void)configUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSubmitButton];
    [self setUpUI];
}

- (void)createSubmitButton {
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    submitButton.backgroundColor = KwBlueColor;
    [submitButton setTitle:@"保存" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitButton.titleLabel.font = KwFont(16.0);
    [submitButton addTarget:self action:@selector(bottomBtnAction) forControlEvents:UIControlEventTouchUpInside];
    submitButton.layer.cornerRadius = 8.0;
    submitButton.layer.masksToBounds = YES;
    [self.view addSubview:submitButton];

    [submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-15 * screenW_6);
        make.right.equalTo(self.view).offset(-20 * screenW_6);
        make.left.equalTo(self.view).offset(20 * screenW_6);
        make.height.equalTo(@(44 * screenW_6));
    }];
}

- (void)setUpUI
{
    self.title = @"照片上传";

//    //创建底部按钮
//    _confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    [_confirmBtn setBackgroundColor:KwBlueColor];
//    [_confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [_confirmBtn setTitle:@"保存" forState:UIControlStateNormal];
//    _confirmBtn.titleLabel.font = KwFont(16.0);
//    [_confirmBtn addTarget:self action:@selector(bottomBtnAction) forControlEvents:UIControlEventTouchUpInside];
//    _confirmBtn.layer.masksToBounds = YES;
//    _confirmBtn.cornerRadius = 5.0;
//    [self.view addSubview:_confirmBtn];
//    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(@-20);
//        make.left.equalTo(@20);
//        make.right.equalTo(@-20);
//        make.height.equalTo(@35);
//    }];

    //每行图片数
    NSInteger imgNum = 4;

    //间隔
    CGFloat imgSpace = 5.0;

    //图片宽度
    CGFloat imgWid = (SCREEN_WIDTH - (imgNum+1)*imgSpace)/imgNum;


    UICollectionViewFlowLayout *collectLayout = [[UICollectionViewFlowLayout alloc] init];
    collectLayout.itemSize = CGSizeMake(imgWid, imgWid);
    collectLayout.minimumLineSpacing = imgSpace;
    collectLayout.minimumInteritemSpacing = imgSpace;
    collectLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    _collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:collectLayout];
    _collectView.backgroundColor = [UIColor whiteColor];
    _collectView.dataSource = self;
    _collectView.delegate = self;
    [self.view addSubview:_collectView];
    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@20);
        make.right.equalTo(@(-20));
        make.bottom.equalTo(self.view).offset(-64 * screenW_6);
    }];

    [_collectView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

    [_collectView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"lastCell"];

    [_collectView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerViewId"];


    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEdit)];
    tap.cancelsTouchesInView = NO;
    [_collectView addGestureRecognizer:tap];
}

#pragma mark - event response
- (void)endEdit {
    [self.view endEditing:YES];
}

////删除按钮
//- (void)deletePicWithBtn:(UIButton *)btn
//{
////    NSInteger tag = btn.tag-100;
////    [_picMutableArr removeObjectAtIndex:tag];
////    [_picParaArr removeObjectAtIndex:tag];
//    [_collectView reloadData];
//    
//    
//    
//}

//删除按钮
- (void)deletePicWithBtn:(UIButton *)btn
{
    //真实的删除
    NSInteger tag = btn.tag-100;
    NSString *urlStr;
    if ([self.picMutableArr[tag] isKindOfClass:[PicListModel class]]) {
         PicListModel *model = self.picMutableArr[tag];
        urlStr = model.imgs;
    }else
    {
        urlStr = self.picMutableArr[tag][@"imgs"];
    }
    NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
    [picRequest startRequestDeleteOnePicWithImgs:urlStr];
    [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
        if (succ)
        {
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            [_picMutableArr removeObjectAtIndex:tag];
            [_collectView reloadData];
        }
    }];
}
- (void)bottomBtnAction
{
    if ([_txtView.text isEqualToString:@"照片描述"]) {
        [SVProgressHUD showInfoWithStatus:@"请完善信息"];
        return;
    }
    
    if (self.isSubmit && self.chooseComplete) {
        self.chooseComplete(_picMutableArr);
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        //移除已经上传的model类
        NSMutableArray *oldPicArr = [[NSMutableArray alloc]initWithArray:_picMutableArr];
        for (int i = (int)(_picMutableArr.count-1); i>=0; i--) {
            if ([_picMutableArr[i] isKindOfClass:[PicListModel class]]) {
                [_picMutableArr removeObjectAtIndex:i];
            }
        }
        if (_picMutableArr.count<=0) {
             self.chooseComplete(oldPicArr);
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"processId":_orderId,@"type":[NSString stringWithFormat:@"%ld",(long)_picType],@"kwPhotoList":[CommonTool beJsonStrWithObj:_picMutableArr]}];
        NWPicManageRequest *picRequest = [[NWPicManageRequest alloc] init];
        [picRequest startRequestAddOnePicWithDic:dic];
        [picRequest completion:^(id result, NSString *message, id extension, BOOL succ) {
            if (succ)
            {
                [SVProgressHUD showSuccessWithStatus:@"保存图片成功"];
                if (self.chooseComplete) {
                    self.chooseComplete(oldPicArr);
                [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
            }
        }];
    }
}

#pragma mark  - Take Photo

- (void)choosePhotoSource
{
    
    if (iOS8Later) {
        UIAlertController *alertControl = [[UIAlertController alloc] init];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
            
        }];
        
        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [self takePhotoFormCamera];
        }];
        
        UIAlertAction *takeLibraryAction = [UIAlertAction actionWithTitle:@"使用相册图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
            [self takePhotoFormLibrary];
        }];
        
        [alertControl addAction:cancelAction];
        [alertControl addAction:takePhotoAction];
        [alertControl addAction:takeLibraryAction];
        
        [self presentViewController:alertControl animated:YES completion:nil];
        
    }else {
        UIActionSheet *photoSheet = [[UIActionSheet alloc] initWithTitle:@"上传图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"使用相册图片", nil];
        [photoSheet showInView:self.view];
    }
    
}

#pragma mark - Photo Method
- (void)takePhotoFormCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }else {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"该设备找不到相机"];
    }
    
}

- (void)takePhotoFormLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [SVProgressHUD show];
    [self presentViewController:picker animated:YES completion:^{
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:TextViewDefaultString]) {
        textView.text = @"";
        textView.textColor = [UIColor blackColor];
    }
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    if (textView.text.length == 0 || [textView.text isEqualToString:@" "]) {
        textView.text = TextViewDefaultString;
        textView.textColor = [UIColor colorWithHexString:@"b5b5b5"];
    } else {
//        NSMutableArray *tempArr = [NSMutableArray array];
        [self.picParaArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [tempArr addObject:@{@"title": textView.text, @"imgs": obj[@"imgs"]}];
            _describStr = textView.text;
        }];
//        self.picParaArr = tempArr.mutableCopy;
    }
    return YES;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (image == nil)
    {
        return;
    }
    //上传
    [self uploadImageWithImage:image];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}
- (void)uploadImageWithImage:(UIImage *)image
{
    [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMddhhmmss"];
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName =  [NSString stringWithFormat:@"%@IMG%@%@.png",kUploadImgPath,str,[Constants createUUID]];
        
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        OSS_Request *request = [[OSS_Request alloc]init];
        [request uploadFileSyscToOSSWithData:imageData destinationFileName:[fileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] progressBlock:nil completeHandler:^(BOOL isSuccess, NSError *error, NSString *url) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            if (isSuccess)
            {
                //图片上传成功
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [_picParaArr addObject:@{@"title":_txtView.text,@"imgs": [NSString stringWithFormat:@"http://kuwo.oss-cn-shanghai.aliyuncs.com/%@",fileName]}];
                    [_picMutableArr addObject:@{@"title":_txtView.text,@"imgs": [NSString stringWithFormat:@"http://kuwo.oss-cn-shanghai.aliyuncs.com/%@",fileName]}];
                    [_collectView reloadData];
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
                });
            }
        }];
    });
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            [self takePhotoFormCamera];
        }
            break;
        case 1:
        {
            [self takePhotoFormLibrary];
        }
            break;
        default:
            break;
    }
}


#pragma mark UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _picMutableArr.count + 1;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == _picMutableArr.count)
    {
        //上传按钮
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lastCell" forIndexPath:indexPath];
        cell.backgroundColor = KwGaryColor;
        UIImageView *imgView = [UIImageView new];
        imgView.backgroundColor = KwGaryColor;
        imgView.image = kImg(@"camera");
        [cell addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(cell.contentView.mas_centerX);
            make.centerY.equalTo(cell.contentView.mas_centerY).offset(-10);
            make.size.mas_equalTo(CGSizeMake(35, 32));
        }];

        UILabel *label = [UILabel new];
        label.font = KwFont(15);
        label.text = @"照片";
        label.textColor = [UIColor lightGrayColor];
        [cell addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(imgView);
            make.top.equalTo(imgView.mas_bottom).offset(10);
        }];
        return cell;
    }
    else
    {
        //其他图片
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        UIImageView *imgView = [UIImageView new];
        imgView.backgroundColor = [UIColor blackColor];
        if ( [_picMutableArr[indexPath.item] isKindOfClass:[UIImage class]]) {
            imgView.image = _picMutableArr[indexPath.item];
        }else if([_picMutableArr[indexPath.item] isKindOfClass:[NSDictionary class]])
        {
            NSURL *imgurl = [NSURL URLWithString:_picMutableArr[indexPath.item][@"imgs"]];
            [imgView sd_setImageWithURL:imgurl];
        }
        else
        {
            NSString *urlStr;
            PicListModel *model = self.picMutableArr[indexPath.item];
            if (model.imgs)
            {
                urlStr = model.imgs;
            }
            else
            {
                urlStr = @"";
            }
            NSURL *imgurl = [NSURL URLWithString:urlStr];
            [imgView sd_setImageWithURL:imgurl];
        }
        
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        [cell addSubview:imgView];
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(@0);
        }];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 100+indexPath.row;
        [btn setImage:kImg(@"delete") forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(deletePicWithBtn:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(@0);
            make.size.mas_equalTo(CGSizeMake(30, 30));
        }];
        
        return cell;
    }
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    CGSize headSize = CGSizeMake(SCREEN_WIDTH, 180 * screenW_6);
    return headSize;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"headerViewId";

    UICollectionReusableView *headview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if (!_txtView) {
        _txtView = [UITextView new];
        _txtView.font = KwFont(14);
        _txtView.delegate = self;
        _txtView.text = [ToolViewViewController isNotNullStr:_describStr]?_describStr:TextViewDefaultString;
        if (self.picParaArr.count > indexPath.row) {
            _txtView.text = [ToolViewViewController isNotNullStr:_describStr]?_describStr: TextViewDefaultString;
            _txtView.textColor = [UIColor blackColor];
        } else {
            _txtView.textColor = [UIColor colorWithHexString:@"b5b5b5"];
        }
    }
    [headview addSubview:_txtView];
    [_txtView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headview);
        make.right.equalTo(headview);
        make.top.equalTo(@10);
        make.bottom.equalTo(@-17);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = KwGaryColor;
    [headview addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.left.right.equalTo(_txtView);
        make.top.equalTo(_txtView.mas_bottom);
    }];
    
    return headview;
}


#pragma mark ---- UICollectionViewDelegate


// 选中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == _picMutableArr.count)
    {
        //添加照片
        [self choosePhotoSource];
    }
    else
    {
        //浏览大图
        
        if ( [_picMutableArr[indexPath.item] isKindOfClass:[UIImage class]]) {
        UIImage *img  = _picMutableArr[indexPath.item];
        [[KwBigImgView shareInstance] showBigImageWithImageStr:img];
        }
        else if([_picMutableArr[indexPath.item] isKindOfClass:[NSDictionary class]])
        {
            NSURL *imgurl = [NSURL URLWithString:_picMutableArr[indexPath.item][@"imgs"]];
            [[KwBigImgView shareInstance] showBigImageWithImageStr:imgurl];
        }
        else
        {
            NSString *urlStr;
            PicListModel *model = self.picMutableArr[indexPath.item];
            if (model.imgs)
            {
                urlStr = model.imgs;
            }
            else
            {
                urlStr = @"";
            }
            NSURL *img = [NSURL URLWithString:urlStr];
            [[KwBigImgView shareInstance] showBigImageWithImageStr:img];
        }

        
    }
}

@end
